/**
 * 这个js对应于卸载选项卡
 */

$(function () {
    // 画饼状图
    // generatePieBlock();
   //  //画柱状图
   // generateBarBlock();

    //面包屑导航监听
    $("#not_offload_breadnav").click(function () {
        $("#not_offload_breadnav").html("<cite style='color: firebrick'>已切割未卸载</cite>");
        $("#offload_breadnav").html("已卸载");
        $("#not_offload_block").css("display","block");
        $("#offload_block").css("display","none");
    });
    $("#offload_breadnav").click(function () {
        $("#offload_breadnav").html("<cite style='color: firebrick'>已卸载</cite>");
        $("#not_offload_breadnav").html("已切割未卸载");
        $("#not_offload_block").css("display","none");
        $("#offload_block").css("display","block");
        generatePieBlock();
    });

    // <!--    已切分未卸载表格-->
    generateNotOffloadTable();
   // <!--检查卸载按钮是否可用-->
    checkOffloadButton();
//    对于卸载按钮的监听
    layui.use(['layer'],function () {
        layer=layui.layer;
        $("#offload_btn").click(function () {
            layer.confirm("即将对于以上任务卸载，是否确认操作？",function () {
                $.ajax({
                    type: 'get',
                    // url:'http://localhost:8778/OffloadSubTask/MecMappingdou',
                    url:offloadUrlPrefix + '/offload/OffloadSubTask/MecMappingdou',
                    async : false,
                    success:function (msg) {
                        console.info(msg);
                        generateNotOffloadTable();
                        // generatePieBlock();
                        checkOffloadButton();
                        // 学姐画拓扑图函数
                        // generateOffloadTopoDiagram(msg);
                        nodegonghuadou(msg);
                    },
                    error: function (msg) {
                        alert(msg.error());
                    }
                });
                layer.msg("成功卸载，详情见底部");
                $("#offload_topodiagram").css("display","block");
                generateOffloadTable();
            });
        })
    });


    <!--    已卸载表格-->
    generateOffloadTable();
//对于性能对比按钮的监听
    layui.use(["layer"],function () {
        $("#offload_display_histogram_btn").click(function () {
            layer.msg("展示成功");
            $("#offload_display_histogram").css("display","block");
            $("#offload_display_histogram_btn").text("点击刷新柱形图");
            $("#offload_display_histogram_btn").attr("class","layui-btn layui-btn-primary");
            // $("#bar").empty();
            //画柱状图（性能对比图）
            generateBarBlock();
        });
    });

    //对于重置卸载的监听
    $('#resetAllOffloadTasksBtn').click(function () {
        $.ajax({
            type: 'get',
            url: offloadUrlPrefix + '/offload/OffloadSubTask/resetAllOffloadTasks',
            success: function () {
                layer.alert('重置成功');
                generateNotOffloadTable();
                generateOffloadTable();
                //向卸载选项卡增加红点
                $("ul.layui-tab-title li:eq(2)").html("任务卸载");
            }

        })
    })
});



//生成未切割表格函数
function generateNotOffloadTable(){
    $("#offload_block").load(location.href+" # offload_block");
    layui.use(['table'],function () {
        var table=layui.table;
        var dataCount=0;
        table.render({
            elem:'#not_offload_table',
            // url:'http://localhost:8778/OffloadSubTask/getAllBeforeOffloadTaskdou',
            url:offloadUrlPrefix + '/offload/OffloadSubTask/getAllBeforeOffloadTaskdou',
            toolbar:false,
            // width:900,
            width:0.9*(document.getElementById("all_tab").offsetWidth),
            title:'未卸载任务表格',
            cols:[[
                {field:'oriTermId',align:'center',title:'父终端号',sort: true},
                {field:'oriTaskId',align:'center',title:'父任务号',sort: true},
                {field:'subTaskId',align:'center',title:'子任务号',sort: true},
                {field:'costTran',align:'center',title:'传输消耗',sort: true},
                {field:'energyCost',align:'center',title:'能量消耗',sort: true}
            ]],
            page: { //支持传入 laypage 组件的所有参数（某些参数除外，如：jump/elem） - 详见文档
                layout: ['limit', 'prev', 'page', 'next', 'skip','count'] //自定义分页布局
                //,curr: 5 //设定初始在第 5 页
                ,groups: 1 //只显示 1 个连续页码
                ,first: false //不显示首页
                ,last: false //不显示尾页

            },
            done:function (res,curr,count) {
                //res：发送url得到的json数据----curr：当前页码----count：数据总量
                var that=this.elem.next();
                if(res.data.length>=5){
                    $.each(res.data,function (index,object) {
                        if(index<=4){
                            that.find(".layui-table-box tbody tr[data-index='"+index+"']").css("background-color","aliceblue");
                        }
                    })
                }

            }
        });
    });
}
//生成卸载表格
function generateOffloadTable(){
    layui.use(['table'],function () {
        var table=layui.table;
        var dataCount=0;
        table.render({
            elem:'#offload_table',
            // url:'http://localhost:8778/OffloadSubTask/getAllAfterOffloadTaskdou',
            url:offloadUrlPrefix + '/offload/OffloadSubTask/getAllAfterOffloadTaskdou',
            toolbar:false,
            title:'已经卸载任务表格',
            // width:900,
            width:0.9*(document.getElementById("all_tab").offsetWidth),
            cols:[[
                {field:'subTaskId',align:'center',title:'子任务号',sort: true},
                {field:'oriTermId',align:'center',title:'父终端号',sort:true},
                {field:'oriTaskId',align:'center',title:'父任务号',sort: true},
                {field:'offMecId',align:'center',color:"red",title:'卸载Mec号',sort: true},
                {field:'costTran',align:'center',title:'传输消耗',sort: true},
                {field:'energyCost',align:'center',title:'能量消耗',sort: true}
            ]],
            page: { //支持传入 laypage 组件的所有参数（某些参数除外，如：jump/elem） - 详见文档
                layout: ['limit', 'prev', 'page', 'next', 'skip','count'] //自定义分页布局
                //,curr: 5 //设定初始在第 5 页
                ,groups: 1 //只显示 1 个连续页码
                ,first: false //不显示首页
                ,last: false //不显示尾页
            }
        });
    });
}


//检查卸载按钮是否可用
function checkOffloadButton() {
    $.ajax({                 //获取表格数量信息
        type:"post",
        // url:"http://localhost:8778/OffloadSubTask/getAllBeforeOffloadTaskdou",
        url:offloadUrlPrefix + "/offload/OffloadSubTask/getAllBeforeOffloadTaskdou",
        dataType:"json",
        success:function (obj) {
            dataCount=obj.count;
            if(dataCount>=5){
                $("#offload_btn").removeAttr("disabled");
                $("#offload_btn").attr("class","layui-btn layui-btn-danger");
                $("#offload_btn").text("点击卸载");

                //向卸载选项卡增加红点
                $("ul.layui-tab-title li:eq(2)").html("任务卸载<span class='layui-badge-dot'></span>");
            }
            else {
                $("#offload_btn").attr("disabled","disabled");
                $("#offload_btn").attr("class","layui-btn layui-btn-disabled");
                $("#offload_btn").text("卸载被禁用(数量不足5)");
                //向卸载选项卡增加红点
                $("ul.layui-tab-title li:eq(2)").html("任务卸载");
            }

        }
    });
}

//画饼图包装函数
function generatePieBlock() {
    $.ajax({
        type: 'get',
        // url:'http://localhost:8778/OffloadSubTask/getAllAfterOffloadTaskdd',
        url:offloadUrlPrefix + '/offload/OffloadSubTask/getAllAfterOffloadTaskdd',
        async : false,
        success:function (msg) {
            drawpie(msg);
        },
        error: function (msg) {
            alert(msg.error());
        }
    });
}

//画条形图包装函数
function generateBarBlock() {
    $.ajax({
        type: 'get',
        // url:'http://localhost:8778/AltTask/getFeedBack',
        url:offloadUrlPrefix + '/offload/AltTask/getFeedBack',
        async : false,
        success:function (msg) {
             console.info(msg);
            if(msg.length==0){
                layer.msg("尚未有任务完成全部卸载！")
            }else {
                drawbar(msg);
            }
        },
        error: function (msg) {
            alert(msg.error());
        }
    })
}

//画饼图细节函数
function drawpie(msg) {
    var myChart = echarts.init(document.getElementById('pie'));
    var option = {
        tooltip: {
            trigger: 'item',
            formatter: "{a} <br/>{b}: {c} ({d}%)"
        },
        legend: {
            orient: 'vertical',
            x: 'left',
            data:['Mec1','Mec2','Mec3','Mec4','Mec5']
        },
        series: [
            {
                name:'卸载任务数',
                type:'pie',
                radius: ['50%', '70%'],
                center: ['50%','50%'],
                avoidLabelOverlap: false,
                label: {
                    normal: {
                        show: false,
                        position: 'center'
                    },
                    emphasis: {
                        show: true,
                        textStyle: {
                            fontSize: '30',
                            fontWeight: 'bold'
                        }
                    }
                },
                labelLine: {
                    normal: {
                        show: false
                    }
                },
                data:[
                    {value:msg[0].count, name:'Mec'+msg[0].mecid},
                    {value:msg[1].count, name:'Mec'+msg[1].mecid},
                    {value:msg[2].count, name:'Mec'+msg[2].mecid},
                    {value:msg[3].count, name:'Mec'+msg[3].mecid},
                    {value:msg[4].count, name:'Mec'+msg[4].mecid}
                ]
            }
        ]
    };
    myChart.setOption(option);
}

//画条形图细节函数
function drawbar(msg) {
    var ListTaskId=[];
    var ListCostB=[];
    var ListCostA=[];

    $.each(msg,function (index,item){
        ListTaskId.push(item.altTaskId);
        ListCostA.push(item.costWithJudge.toFixed(2));
        ListCostB.push(item.costWithoutJudge.toFixed(2));
    });
    var myChart = echarts.init(document.getElementById('bar'));
    var option = {
        title: {
            text: '本地与卸载能耗代价对比详情',
        },
        tooltip: {
            trigger: 'axis',
            axisPointer: {
                type: 'shadow'
            }
        },
        legend: {
            data: ['卸载决策前', '卸载决策后']
        },
        grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            containLabel: true
        },
        xAxis: {
            type: 'value',
            boundaryGap: [0, 0.01]
        },
        yAxis: {
            max: '750px',
            type: 'category',
            data: ListTaskId,
            axisLabel : {
                formatter: 'Task{value}'
            }
        },
        series: [
            {
                name: 'Cost Without Judge',
                type: 'bar',
                data: ListCostB,

                itemStyle: {
                    normal: {
                        label: {
                            show: true, //开启显示
                            position: 'right', //在上方显示
                            textStyle: { //数值样式
                                color: 'red',
                                fontSize: 12
                            }
                        },
                        color:'#d48265'
                    }
                }
            },
            {
                name: 'Cost With Judge',
                type: 'bar',
                data: ListCostA,
                itemStyle: {
                    normal: {
                        label: {
                            show: true, //开启显示
                            position: 'right', //在上方显示
                            textStyle: { //数值样式
                                color: 'darkblue',
                                fontSize: 12
                            }
                        },
                        color:'#91c7ae'
                    }

                }
            }
        ]
    };
// 使用刚指定的配置项和数据显示图表。
    myChart.setOption(option);
}

//画卸载的拓扑图
function generateOffloadTopoDiagram(matching_results){

    // $.ajax({
    //     type: 'get',
    //     url: 'http://localhost:8778/OffloadSubTask/MecMappingdou',
    //     async: false,
    //     dataType: 'json',
    //     success: function (msg) {
    //         matching_results = msg;
    //
    //     },
    //     error: function (XMLHttpResponse, textStatus, errorThrown) {
    //         console.log("1 异步调用返回失败,XMLHttpResponse.readyState:" + XMLHttpResponse.readyState);
    //         console.log("2 异步调用返回失败,XMLHttpResponse.status:" + XMLHttpResponse.status);
    //         console.log("3 异步调用返回失败,textStatus:" + textStatus);
    //         console.log("4 异步调用返回失败,errorThrown:" + errorThrown);
    //     }
    // });
    var json_data = matching_results;
    var mec_node = [], unloaded_task = [];
    layui.use('layer', function () {
        var layer = layui.layer, $ = layui.jquery;
        $(function () {
            for (var i = 0; i < json_data.length; i++) {
                mec_node.push(json_data[i].offMecId);
                unloaded_task.push(json_data[i].subTaskId);
            }

            var stage = new JTopo.Stage(canvas);
            //显示工具栏
            var scene = new JTopo.Scene();
            stage.add(scene);
            scene.background = '../../static/img/edgecompute/bg.png';

            var MEC_NODE = [], TASK_NODE = [];
            for (var i = 0; i < mec_node.length; i++) {                     //生成MEC节点
                var MEC_Node = new JTopo.CircleNode('Mec' + mec_node[i]);
                MEC_Node.fillColor = '205,190,112';
                MEC_Node.radius = 22;
                MEC_Node.setImage('../../static/img/edgecompute/mec.png', true);
                MEC_Node.id =  'mec'+ mec_node[i];
                MEC_Node.textPosition = 'Bottom_Center';
                MEC_Node.fontColor = '0, 0, 0';
                MEC_Node.setLocation(140 * mec_node[i], 370);
                MEC_Node.layout = { type: 'circle', radius: 220 };
                scene.add(MEC_Node);
                MEC_NODE.push(MEC_Node);

                MEC_Node.mouseover(function () {
                    var content=this.id;
                    layer.msg(content);
                });
                MEC_Node.mouseout(function () {
                    layer.closeAll();
                })
            }

            for (var i = 0; i < unloaded_task.length; i++) {                     //生成任务节点
                var TASK_Node = new JTopo.Node('task' + unloaded_task[i]);
                TASK_Node.setSize(40, 40);
                TASK_Node.fillColor = '152,182,109';
                TASK_Node.id = 'task' + unloaded_task[i];
                TASK_Node.textPosition = 'Top_Center';
                TASK_Node.fontColor = '0, 0, 0';
                TASK_Node.setLocation(40 + 140 * i, 100);
                TASK_Node.layout = { type: 'circle', radius: 220 };
                scene.add(TASK_Node);
                TASK_NODE.push(TASK_Node);

                TASK_Node.mouseover(function () {
                    var content = "任务"+this.id;
                    // layer.tips(content, that, {
                    //     tips: [3, '#79bdcc'],
                    //     time: 0
                    // });
                    layer.msg(content);
                });
                TASK_Node.mouseout(function () {
                    layer.closeAll();
                });
            }

            var LINK_1 = [], LINK_2 = [];

            for (let j = 0; j < unloaded_task.length; j++) {
                var link_1 = new JTopo.Link(TASK_NODE[j], MEC_NODE[j]);
                link_1.strokeColor = '152,182,109';
                if(j==0) {
                    link_1.text = '卸载';
                    link_1.fontColor = '152,182,109';
                }
                link_1.alpha = 0;
                link_1.dashedPattern = 5;
                link_1.arrowsRadius = 15;
                scene.add(link_1);
                LINK_1.push(link_1);

                var link_2 = new JTopo.Link(MEC_NODE[j], TASK_NODE[j]);
                link_2.strokeColor = '205,190,112';
                if(j == unloaded_task.length-1){
                    link_2.text = '结果返回';
                    // link_2.siz
                    link_2.fontColor = '205,190,112';
                }
                link_2.alpha = 0;
                link_2.bundleGap = 20;        //间距
                link_2.dashedPattern = 5;     //虚线
                link_2.arrowsRadius = 15;     //箭头
                scene.add(link_2);
                LINK_2.push(link_2);
            }

            function return_gif(i, n) {
                if (n > 1) {
                    return;
                }
                LINK_1[i].alpha = 0;
                LINK_2[i].alpha = n;
                setTimeout(function () {
                    return_gif(i, n + 0.2);
                }, 100);
            }

            function offload_gif(i, n, callback) {
                if (n > 1) {
                    setTimeout(function () {
                        callback(i, 0);
                    }, json_data[i].energyCost);
                    return;
                }
                LINK_1[i].alpha = n;
                setTimeout(function () {
                    offload_gif(i, n + 0.1, callback);
                }, 100);
            }

            for(let k=0; k<LINK_1.length; k++) {
                offload_gif(k,0, return_gif);
            }

        });
    });
}

//飘零
function nodegonghuadou(msg) {

    $(document).ready(function () {
        //var canvas = document.getElementById('offload_topo_show');
        //多次点击时 重置拓扑图
        $('#offload_topo_show').remove();
        $('#offload_topo').append('<canvas id="offload_topo_show" height="400px" width="800px"></canvas>');
        
        var canvas = document.getElementById('offload_topo_show');
        var ctx = canvas.getContext('2d');
        // ctx.clearRect(0,0,canvas.width,canvas.height);

        var stage = new JTopo.Stage(canvas);
        var scene = new JTopo.Scene(stage);
        stage.frames = 24;
        //scene.background = './img/bg.jpg'; //不写默认空白

        //加入mec结点 制定mec的位置和颜色数组
        var mecx=[];
        //var meccolor=['#005aab','#274862','#995054','#d96831','#e6b33d'];
        var meccolor = ["0,90,171","39,72,98","153,80,84","217,104,49","230,179,61"];
        for (var i = 0; i < 5; i++) {
            var x = 50 + i * 150;
            var mecid = i+1;
            mecx[i]= x;
            //颜色字典
            // var color = JTopo.util.randomColor();
            // meccolor[i]=color;
            var cloudNode = new JTopo.Node("Mec" + mecid);
            cloudNode.textPosition = 'Bottom_Center';
            cloudNode.fontColor = '0, 0, 0'; //字体颜色
            cloudNode.setLocation(x, 300);
            cloudNode.setImage('../../static/img/edgecompute/mec1.png', true);
            scene.add(cloudNode);
        }

        //循环添加位置
        var al = [];
        for (var i = 0; i < msg.length; i++) {
            var offmecid = msg[i].offMecId;
            var x0 = mecx[offmecid-1];
            var t = {x: x0 , y: 300, rotate: 2 * Math.PI, alpha: 0.3};
            al[i] = t
        }

        for (var i = 0; i < al.length; i++) {
            var subid = msg[i].subTaskId;
            var node = new JTopo.Node("子任务" + subid);
            var mecid = msg[i].offMecId;
            node.textPosition = 'Middle_Center';
            node.font = '12px 微软雅黑';
            node.setSize(60, 50);
            node.setCenterLocation(80 + i * 150, 80);
            node.fillColor = meccolor[mecid-1]; // 颜色
            scene.add(node);
            JTopo.Animate.stepByStep(node, al[i], 7000, true).start();
        }
    });
}